export class Line{
    constructor(options, {x = 0, y = 0, sx = 0, sy = 0, ex = 0, ey = 0, width = 1, rotation = 0, color = 'red', ctx = null} = options){
        Object.assign(this, {x, y, sx, sy, ex, ey, width, color, ctx, options})
        this._rotation = 0
        this.rotation = rotation
    }
    get rotation(){
        return this._rotation
    }
    set rotation(r){
        let rotation = Math.atan2(this.ey - this.sy, this.ex - this.sx) //求旋转角度
        r = r * Math.PI / 180
        this._rotation = r + rotation
        this.__rotation = r
    }
    setEY(newEY){
        this.ey = newEY
        let rotation = Math.atan2(this.ey - this.sy, this.ex - this.sx) //求旋转角度
        this._rotation = this.__rotation + rotation
    }
    
    getRect(){
        let x = this.ex - this.sx, y = this.ey - this.sy
        // let rotation = Math.atan2(y, x) + this.rotation//求旋转角度
        let len = Math.sqrt(x * x + y * y)//求直角三角形斜边长

        y = Math.sin(this._rotation) * len//高度
        x = Math.sin(Math.PI / 2 - this._rotation) * len//长度
        return {sx: this.sx + this.x, sy: this.sy + this.y, ex: this.x + this.sx + x, ey: this.y + this.sy + y}
    }
    draw(ctx = null){
        ctx = ctx || this.ctx
        ctx.save()
        ctx.strokeStyle = this.color
        ctx.beginPath()
        
        let rect = this.getRect()
        ctx.strokeRect(rect.sx, rect.sy, rect.ex - rect.sx, rect.ey - rect.sy)
        ctx.translate(this.x, this.y)
        ctx.rotate(this.__rotation)
        ctx.moveTo(this.sx, this.sy)
        ctx.lineTo(this.ex, this.ey)
        ctx.stroke()
        ctx.restore()
    }
}